package aynu.oracle.video.config;

import aynu.oracle.video.component.LoginHandlerInterceptor;
import aynu.oracle.video.component.MyLocaleResolver;
import aynu.oracle.video.filters.CORSFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 自定义配置类
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //浏览器发送 / 请求来到 index
        registry.addViewController("/").setViewName("upload.html");
//        registry.addViewController("/index.html").setViewName("login");
//        registry.addViewController("/main.html").setViewName("dashboard");
    }

    // 下面的配置中，方法名不能更换，是固定配置
//    @Bean
//    public LocaleResolver localeResolver(){
//        return new MyLocaleResolver();
//    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 处理静态资源
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/index.html","/","/login","/css/**", "/js/**","/img/**", "/video/**", "/file/**");
    }

    @Bean
    public FilterRegistrationBean<CORSFilter> abcFilter() {
        FilterRegistrationBean<CORSFilter> filterRegBean = new FilterRegistrationBean<>();
        filterRegBean.setFilter(new CORSFilter());
        filterRegBean.addUrlPatterns("/api/*");
        filterRegBean.setOrder(Ordered.LOWEST_PRECEDENCE -1);
        return filterRegBean;
    }

    // 获取当前系统的类型，设置对于的本地资源路径，用来解决上传视频后，需要重复发布才能观看的问题
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\file\\";
        String os = System.getProperty("os.name");
//        System.out.println("os___"+os+"_____path___"+path);
        if (os.toLowerCase().startsWith("win")) {
            registry.addResourceHandler("/file/**").
                    addResourceLocations("file:"+path);
        }else{         //linux和mac系统 可以根据逻辑再做处理
            registry.addResourceHandler("/file/**").
                    addResourceLocations("file:"+path);
        }
    }
}
